const bodyParser=require("body-parser")
const {getStoreDB}=require("./mongo")
const {getStoreDB}=require("./mongo")
const cookieParser=require("cookie-parser")
app.use(bodyParser.json());
app.use(cookieParser())
app.use('/user', userRouter);
userRouter.post("/register",function(req,res){
    getStoreDB(function(storeDB){
        storeDB.collection("userinfo").insert(req.body,function(err,result){
         if(err){
             res.send({
                status: 10001,
                msg: err.message
             })
             return
         }
         res.send({
            status: Const.SUCCESSFUL,
            msg: 'ok',
            data: {
                user_id: result.insertedId
            }
         })
        })
    })
})


userRouter.post("/login",function(req,res){
    getStoreDB(function(storeDB){
        storeDB.collection("userinfo").find({login_name:req.body.login_name,password:req.body.password}).toArray(function(err,result){
         if(err){
             res.send({
                status: 10001,
                msg: err.message
             })
             return
         }
         const token=jwt.sign({login_name:req.body.login_name},key)
         res.cookie("token",token)
         if(result.length!==0){
            res.send({
                status: Const.SUCCESSFUL,
                msg: 'ok',
                data: {
                    user_id: result.insertedId
                }
             }) 
         }
        })
    })
})

module.exports={
    userRouter
}